# Q-Project
# Views Module
# Copyright (C) 2010 by Andres Rocha, Miguel Ordo/ez, Edgar Sotelo
# 
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from django.shortcuts import render_to_response
#from django.core.context_processors import csrf
from django.http import HttpResponseRedirect
from django.core.mail import EmailMessage
from Q.QApp.models import User, Question, Category_User, Reply
from Q.QApp.forms import userForm, loginForm, profileForm, categoryForm, questionForm, replyButton, replyForm
from Q.settings import EMAIL_HOST_USER
import hashlib

def main(request):
    return render_to_response('index.html',{'register':userForm(),'login':loginForm()})

def logout(request):
    del request.session['UserId']
    del request.session['Mail']
    del request.session['UserName']
    return render_to_response('index.html',{'register':userForm(),'login':loginForm()})
    
def topic(request):

    if request.session.get('UserId'):
        return render_to_response('edit_topic.html',{'topic':categoryForm()})
    else:
        return render_to_response('index.html',{'register':userForm(),'login':loginForm(),'msg':'No has iniciado sesion!'})
            
def profile(request):
    if request.session.get('UserId'):
        user = User.objects.get(mail=request.session.get('Mail'))
        data = {'name': user.name, 'last_name': user.last_name}
        return render_to_response('edit_profile.html',{'profile':profileForm(initial=data)})
    else:
        return render_to_response('index.html',{'register':userForm(),'login':loginForm(),'msg':'No has iniciado sesion!'})


def topic_save(request):
    if request.method == 'POST' and request.session.get('UserId'):
        form = categoryForm(request.POST)
        if form.is_valid():
            newSubject         = form.cleaned_data['subject']
            del form.cleaned_data['subject']
            user = User.objects.get(mail = request.session['Mail'])
            cat = Category_User(subject=newSubject)
            questions_raw = Question.objects.filter(user = user)
            questions = []
            for x in questions_raw:
                ls = []
                ls.append(x)
                ls.append(replyButton(initial={'question':x.id}))
                questions.append(ls)
                
            cat.save()
            try:
#                cat.save()
                cat.user.add(user)
                topics_raw = Category_User.objects.filter(user = user)
                topics = []
                for x in topics_raw:
                    topics.append(x.get_subject_display())
                    cats = Category_User.objects.filter(user = user)
                questionsOthers_raw = []
                questionsOthers = []
                for x in cats:
                    questionsOthers_raw.append(Question.objects.filter(subject = x))
                for x in questionsOthers_raw:
                    if x:
                        for y in x:
                            questionsOthers.append(y.__unicode__())
                            
                    return render_to_response('home.html',{'user':request.session['UserName'],'msg':'Cambios guardados','topics':topics,
                                                       'question':questionForm(),'questions':questions, 'questionsOthers':questionsOthers})
            except:
                topics_raw = Category_User.objects.filter(user = user)
                topics = []
                for x in topics_raw:
                    topics.append(x.get_subject_display())
                    
                cats = Category_User.objects.filter(user = user)
                questionsOthers_raw = []
                questionsOthers = []
                
                for x in cats:
                    questionsOthers_raw.append(Question.objects.filter(subject = x))
                    
                for x in questionsOthers_raw:
                    questionsOthers.append(x.__unicode__())
                    
                return render_to_response('home.html',{'user':request.session['UserName'],'msg':'Hubo un error al guardar','topics':topics,
                                                       'question':questionForm(),'questions':questions, 'questionsOthers':questionsOthers})
    else:
        return render_to_response('index.html',{'register':userForm(),'login':loginForm(),'msg2':'No has iniciado sesion'})

def profile_save(request):
    if request.method == 'POST' and request.session.get('UserId'):
        form = profileForm(request.POST)
        if form.is_valid():
            newName         = form.cleaned_data['name']
            newLast_name    = form.cleaned_data['last_name']
            newPassword     = form.cleaned_data['password']
            del form.cleaned_data['name']
            del form.cleaned_data['last_name']
            del form.cleaned_data['password']
            user = User.objects.get(mail = request.session['Mail'])
            user.name = newName
            user.last_name = newLast_name
            sessionUser = newName
            if newPassword != '':
                user.password = newPassword
                
            topics_raw = Category_User.objects.filter(user = user)
            topics = []
            for x in topics_raw:
                    topics.append(x.get_subject_display())
             
             
            questions_raw = Question.objects.filter(user = user)
                
            questions = []
            for x in questions_raw:
                ls = []
                ls.append(x)
                ls.append(replyButton(initial={'question':x.id}))
                questions.append()
                    
            questions_raw = Question.objects.filter(user = user)
            questions = []           
            
            for x in questions_raw:
                questions.append(x.__unicode__())
                
            cats = Category_User.objects.filter(user = user)
            questionsOthers_raw = []
            questionsOthers = []
                                
            for x in cats:
                questionsOthers_raw.append(Question.objects.filter(subject = x))
                    
            for x in questionsOthers_raw:
                if x:
                    for y in x:
                        questionsOthers.append(y.__unicode__())

            try:
#                sendMail('Cambio exitoso',newMail,newPassword)
                user.save()                    
                request.session['UserName'] = sessionUser
                return render_to_response('home.html',{'user':request.session['UserName'],'msg':'Cambios guardados','topics':topics,
                                                       'question':questionForm(),'questions':questions, 'questionsOthers':questionsOthers})
            except:
               return render_to_response('home.html',{'user':request.session['UserName'],'topics':topics,'msg':'Hubo un error al guardar',
                                                       'question':questionForm(),'questions':questions, 'questionsOthers':questionsOthers})
    else:
        return render_to_response('index.html',{'register':userForm(),'login':loginForm(),'msg2':'No has iniciado sesion'})

def session(request):
    if request.method == 'POST':
        form = loginForm(request.POST)
        if form.is_valid():
            MailCompare        = form.cleaned_data['mail']
            PasswordCompare    = form.cleaned_data['password']
            try:
                user = User.objects.get(mail=MailCompare, password=PasswordCompare)
                del form.cleaned_data['mail']
                del form.cleaned_data['password']
                request.session['UserId']		= hash(user.mail)
                request.session['Mail']			= user.mail
                request.session['UserName']		= user.name
                
                topics_raw = Category_User.objects.filter(user = user)
                topics = []
                
                for x in topics_raw:
                    topics.append(x.get_subject_display())
                questions_raw = Question.objects.filter(user = user)
                
                questions = []
                for x in questions_raw:
                    ls = []
                    ls.append(x)
                    ls.append(replyButton(initial={'question':x.id}))
                    questions.append(ls)

                    
                cats = Category_User.objects.filter(user = user)
                questionsOthers_raw = []
                questionsOthers = []
                                
                for x in cats:
                    questionsOthers_raw.append(Question.objects.filter(subject = x))
                    
                for x in questionsOthers_raw:
                    if x:
                        for y in x:
                            questionForms = []
                            questionForms.append(y)
                            questionForms.append(replyButton(initial={'question':y.id}))
                            questionsOthers.append(questionForms)

                return render_to_response('home.html',{'user':request.session['UserName'],'topics':topics,'question':questionForm(),'questions':questions,'questionsOthers':questionsOthers})
            except:
                return render_to_response('index.html',{'register':userForm(),'login':loginForm(),'msg2':'Usuario no registradoF'})
        else:
            return render_to_response('index.html',{'register':userForm(),'login':loginForm(),'msg2':'Falta algun campo'})
    else:
        return render_to_response('index.html',{'register':userForm(),'login':loginForm(),'msg2':'No has iniciado sesion'})

def register(request):
    if request.method == 'POST':
        form = userForm(request.POST)
        if form.is_valid():
            newName        = form.cleaned_data['name']
            newLast_name   = form.cleaned_data['last_name']
            newMail        = form.cleaned_data['mail']
            newPassword    = form.cleaned_data['password']
            newUser = User(name = newName, last_name = newLast_name, mail = newMail, password = newPassword)
            del form.cleaned_data['name']
            del form.cleaned_data['last_name']
            del form.cleaned_data['mail']
            del form.cleaned_data['password']
            try:
#                sendMail('Registro exitoso',newMail,newPassword)
                newUser.save()
                return render_to_response('register.html', {'login':loginForm(),'title':'Registrado'})
            except:
                return render_to_response('index.html',{'register':userForm(),'login':loginForm(),'msg':'Error al guardar!'})
        else:
            return render_to_response('index.html',{'register':userForm(),'login':loginForm(),'msg':'Falta algun campo!'})
    else:
        return render_to_response('index.html',{'register':userForm(),'login':loginForm()})

def new_user_correct(request): 
   return render_to_response('register.html', {'title':'Registrado'})

def sendMail(msg,mail,password):
    mailSend = EmailMessage(msg, 'Estas registrado exitosamente con el usuario '
                            +mail+ ' y con el password '+password,EMAIL_HOST_USER , [mail])
    print msg, mail, password
    print mailSend.send()
    
def question_save(request):
    if request.method == 'POST' and request.session.get('UserId'):
        
        user = User.objects.get(mail = request.session['Mail'])
        topics_raw = Category_User.objects.filter(user = user)
        topics = []
        for x in topics_raw:
            topics.append(x.get_subject_display())
        
        form = questionForm(request.POST)
        if form.is_valid():
            newQuestion     = form.cleaned_data['question']
            newSubject      = form.cleaned_data['subject']
            del form.cleaned_data['question']
            del form.cleaned_data['subject']          
            question = Question(user = user, question = newQuestion,
                                subject = newSubject)
            
            topics_raw = Category_User.objects.filter(user = user)
            topics = []
            for x in topics_raw:
                topics.append(x.get_subject_display())
            
            try:

                question.save()
                questions = []
                for x in questions_raw:
                    ls = []
                    ls.append(x)
                    ls.append(replyButton(initial={'question':x.id}))
                    questions.append(ls)
                    
            
                cats = Category_User.objects.filter(user = user)
                questionsOthers_raw = []
                questionsOthers = []
                                
                for x in cats:
                    questionsOthers_raw.append(Question.objects.filter(subject = x))
                    
                for x in questionsOthers_raw:
                    if x:
                        for y in x:
                            questionsOthers.append(y)
                    
                return render_to_response('home.html',{'user':request.session['UserName'],'msg':'Cambios guardados','topics':topics,
                                                       'question':questionForm(),'questions':questions})
            except:
                questions_raw = Question.objects.filter(user = user)
                questions = []
                
                for x in questions_raw:
                    questions.append(x.__unicode__())
                   
                cats = Category_User.objects.filter(user = user)
                questionsOthers_raw = []
                questionsOthers = []
                
                for x in cats:
                    questionsOthers_raw.append(Question.objects.filter(subject = x))
                    
                for x in questionsOthers_raw:
                    questionsOthers.append(x)
                
                return render_to_response('home.html',{'user':request.session['UserName'],'msg':'Hubo un error al guardar','topics':topics,
                                                       'question':questionForm(),'questions':questions, 'questionsOthers':questionsOthers})
    
        else:
            questions_raw = Question.objects.filter(user = user)
            questions = []
                
            for x in questions_raw:
                questions.append(x.__unicode__())
                
            cats = Category_User.objects.filter(user = user)
            questionsOthers_raw = []
            questionsOthers = []
                
            for x in cats:
                questionsOthers_raw.append(Question.objects.filter(subject = x))
                    
            for x in questionsOthers_raw:
                if x:
                    for y in x:
                        questionsOthers.append(y.__unicode__())
                    
            return render_to_response('home.html',{'user':request.session['UserName'],'msg':'Pregunta vacia','topics':topics,
                                                       'question':questionForm(),'questions':questions, 'questionsOthers':questionsOthers})

    else:
        return render_to_response('index.html',{'register':userForm(),'login':loginForm(),'msg2':'No has iniciado sesion'})
        
def reply(request):
    if request.method == 'POST' and request.session.get('UserId'):
        
        form = replyButton(request.POST)
        if form.is_valid():
            
            q = form.cleaned_data['question']
            del form.cleaned_data['question']
            question = Question.objects.get(id = q)
            reply_raw = Reply.objects.filter(question = q)
        
            return render_to_response('question.html', {'reply':replyForm(initial={'question' : q}),'question':question,'replies':reply_raw})
        else :
            return render_to_response('index.html',{'register':userForm(),'login':loginForm()})
    
    else :
        return render_to_response('index.html',{'register':userForm(),'login':loginForm()})
        

def reply_save(request):
    if request.method == 'POST' and request.session.get('UserId'):
        form = replyForm(request.POST)
        if form.is_valid():
            user = User.objects.get(mail = request.session['Mail'])
            q   = form.cleaned_data['question']
            rep = form.cleaned_data['reply']
            question = Question.objects.get(id = q)
    
            reply = Reply(user = user, question = question,reply = rep, file ="")
            reply_raw = []
        
        
            try:
                reply.save()
                reply_raw = Reply.objects.filter(question = q)
                
                return render_to_response('question.html', {'reply':replyForm(initial={'question' : q}),'question':question, 'replies':reply_raw})
                
            except:
                reply_raw = Reply.objects.filter(question = q)
                return render_to_response('question.html', {'reply':replyForm(initial={'question' : q}),'question':question, 'replies':reply_raw})
            
    else:
        return render_to_response('index.html',{'register':userForm(),'login':loginForm()})

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        